package com.zs.games.utils;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @program: WAB_IM_System
 * @description: 时间戳工具类
 * @author: LiX
 * @create: 2020-06-30 19:12
 **/
public class SystemClock {
    private static final String THREAD_NAME = "system.clock";

    private static final SystemClock MILLIS_CLOCK = new SystemClock(50);

    private final long precision;

    private final AtomicLong now;

    private SystemClock(long precision) {
        this.precision = precision;
        this.now = new AtomicLong(System.currentTimeMillis());
        scheduleClockUpdating();
    }

    public static SystemClock millisClock() {
        return MILLIS_CLOCK;
    }

    private void scheduleClockUpdating() {
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(runnable -> {
            Thread thread = new Thread(runnable, THREAD_NAME);
            thread.setDaemon(true);
            return thread;
        });
        scheduler.scheduleAtFixedRate(() -> now.set(System.currentTimeMillis()), precision, precision, TimeUnit.MILLISECONDS);
    }

    public long now() {
        return now.get();
    }
}
